package com.zzsy.carosshopprojects.activitys.home.mainpage.common.scan;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;

import com.king.base.util.ToastUtils;
import com.yzy.voice.VoicePlay;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.activitys.home.mainpage.common.payresult.PayResultAc;
import com.zzsy.carosshopprojects.base.BaseActivity;
import com.zzsy.carosshopprojects.bean.MessageEvent;
import com.zzsy.carosshopprojects.util.AlgorithmUtil;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.util.zxing.activity.CaptureFragment;
import com.zzsy.carosshopprojects.util.zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

/**
 * 首页收费-支付的扫描
 */
public class ScanOnlyAc extends BaseActivity {
    public static void start(Context mactivity, String num, String payAmount, String payType, String orderNumber) {
        Intent intent = new Intent(mactivity, ScanOnlyAc.class);
        intent.putExtra("num", num);
        intent.putExtra("payAmount", payAmount);
        intent.putExtra("payType", payType);
        intent.putExtra("orderNumber", orderNumber);
        mactivity.startActivity(intent);
    }

    private ScanOnlyMode scanOnlyMode;

    @Override
    protected int bindLayout() {
        return R.layout.ac_scanonly;
    }

    @Override
    protected void initView() {
        initTitle(getWindow().getDecorView(), getResources().getString(R.string.Collection), this);
        CaptureFragment captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        /**
         * 替换我们的扫描控件
         */
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
    }

    @Override
    protected void initData() {
        scanOnlyMode = getViewModelProvider().get(ScanOnlyMode.class);

    }

    @Override
    protected void loadMethod() {
        tokenResult();
        orderPayResult();
    }

    /**
     * token 处理结果
     */
    private void tokenResult() {
        scanOnlyMode.getLive().observe(ScanOnlyAc.this, tokenBean -> {
            if (!StringUtils.isEmpty(tokenBean.getToken())) {
                postJson(tokenBean.getToken(), tokenBean.getResult());
            } else {
                ToastUtils.showToast(getApplicationContext(), getApplicationContext().getResources().getString(R.string.dataError));
                finish();
            }
        });
    }

    /**
     * 订单支付结果
     */
    private void orderPayResult() {
        scanOnlyMode.getLiveResult().observe(this, resultBean -> {
            Log.d("xxxxxxxaaa", resultBean.getCode() + "");
            String payAmount = AlgorithmUtil.getAmount(getIntent().getStringExtra("payAmount"), 100);
            switch (resultBean.getCode()) {
                case 200:
                    if (DataUtil.getInstance().getMusicSwitch().equals("1")) {
                        VoicePlay.with(ScanOnlyAc.this).play(payAmount, false);
                    }
                    break;
                case 502:

                    break;
                case 503:

                    break;
                default:
                    ToastUtils.showToast(getApplicationContext(), resultBean.getMessage());
                    break;
            }
            PayResultAc.start(ScanOnlyAc.this, getIntent().getStringExtra("orderNumber"), resultBean.getCode() + "", payAmount, "0");
            /**支付操作后关闭之前的页面**/
            EventBus.getDefault().post(new MessageEvent(MessageEvent.ACTIVITYCLOSE));
            finish();

        });
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {

            if (getIntent().getStringExtra("num").equals("5")) {
                //HUD.getInstance().show(ScanOnlyAc.this, "支付中...");
                String code;
                try {
                    code = result.substring(0, 2);
                } catch (Exception e) {
                    ToastUtils.showToast(getApplicationContext(), "扫码失败,请从新扫码");
                    finish();
                    return;
                }

                if (getIntent().getStringExtra("payType").equals("020"))//支付宝
                {
                    if (!code.equals("28")) {
                        ToastUtils.showToast(getApplicationContext(), "请使用支付宝付款码");
                        finish();
                        return;
                    }

                } else if (getIntent().getStringExtra("payType").equals("010"))//微信
                {
                    if (code.equals("10") || code.equals("11") || code.equals("12") || code.equals("13") || code.equals("14") || code.equals("15")) {

                    } else {
                        ToastUtils.showToast(getApplicationContext(), "请使用微信付款码");
                        finish();
                        return;
                    }
                }

                scanOnlyMode.getToken(ScanOnlyAc.this, result);
            }
        }

        @Override
        public void onAnalyzeFailed() {
            ToastUtils.showToast(getApplicationContext(), getResources().getString(R.string.erCodeFail));
            finish();
        }
    };

    private void postJson(String token, String result) {
        Map<String, String> map = new HashMap<>();
        map.put("payType", getIntent().getStringExtra("payType"));
        map.put("orderNumber", getIntent().getStringExtra("orderNumber"));
        map.put("authCode", result);
        map.put("payAmount", getIntent().getStringExtra("payAmount"));
        map.put("storeId", DataUtil.getInstance().getStoreId());
        map.put("terminalId", DataUtil.getInstance().getTerminalId());
        scanOnlyMode.OrderPay(ScanOnlyAc.this, map, token);
    }


}
